﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace Agricultural_Sales.ASP
{
    public partial class MyOrder : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // 检查用户是否已登录
            if (Session["UserId"] == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }

            if (!IsPostBack)
            {
                // 隐藏支付信息区域
                paymentInfo.Visible = false;
            }
        }

        // 显示支付信息按钮点击事件
        protected void btnShowPayment_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            int orderId = Convert.ToInt32(btn.CommandArgument);

            // 设置支付信息数据源参数
            SqlDataSourcePayment.SelectParameters["OrderId"].DefaultValue = orderId.ToString();

            // 显示支付信息区域
            paymentInfo.Visible = true;

            // 重新绑定支付信息
            FormViewPayment.DataBind();
        }

        // 订单操作按钮点击事件
        protected void btnOrderAction_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            string action = btn.CommandName;
            int orderId = Convert.ToInt32(btn.CommandArgument);

            try
            {
                switch (action)
                {
                    case "Pay":
                        ProcessPayment(orderId);
                        break;
                    case "Cancel":
                        CancelOrder(orderId);
                        break;
                    case "Refund":
                        ProcessRefund(orderId);
                        break;
                    case "Confirm":
                        ConfirmOrder(orderId);
                        break;
                }

                // 刷新GridView
                GridViewMyOrders.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('操作失败：{ex.Message}');</script>");
            }
        }

        // 处理付款
        private void ProcessPayment(int orderId)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    try
                    {
                        // 更新订单状态为已支付
                        string updateOrderSql = "UPDATE [Order] SET OrderState = '已支付', UpdateAt = GETDATE() WHERE OrderId = @OrderId AND OrderState = '待支付'";
                        using (SqlCommand cmd = new SqlCommand(updateOrderSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@OrderId", orderId);
                            int rowsAffected = cmd.ExecuteNonQuery();

                            if (rowsAffected == 0)
                            {
                                throw new Exception("订单状态已改变，无法完成支付");
                            }
                        }

                        // 更新支付状态为支付成功
                        string updatePaymentSql = "UPDATE Payment SET PayState = '支付成功', PayTime = GETDATE() WHERE OrderId = @OrderId";
                        using (SqlCommand cmd = new SqlCommand(updatePaymentSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@OrderId", orderId);
                            cmd.ExecuteNonQuery();
                        }

                        transaction.Commit();
                        Response.Write("<script>alert('支付成功！');</script>");
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }

        // 取消订单
        private void CancelOrder(int orderId)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    try
                    {
                        // 获取当前订单状态
                        string getOrderStateSql = "SELECT OrderState FROM [Order] WHERE OrderId = @OrderId";
                        string currentState = "";
                        using (SqlCommand cmd = new SqlCommand(getOrderStateSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@OrderId", orderId);
                            currentState = cmd.ExecuteScalar()?.ToString();
                        }

                        if (currentState == "已取消" || currentState == "已完成")
                        {
                            throw new Exception("该订单无法取消");
                        }

                        // 更新订单状态为已取消
                        string updateOrderSql = "UPDATE [Order] SET OrderState = '已取消', UpdateAt = GETDATE() WHERE OrderId = @OrderId";
                        using (SqlCommand cmd = new SqlCommand(updateOrderSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@OrderId", orderId);
                            cmd.ExecuteNonQuery();
                        }

                        // 如果是已支付订单，更新支付状态为已退款
                        if (currentState == "已支付")
                        {
                            string updatePaymentSql = "UPDATE Payment SET PayState = '已退款', PayTime = GETDATE() WHERE OrderId = @OrderId";
                            using (SqlCommand cmd = new SqlCommand(updatePaymentSql, conn, transaction))
                            {
                                cmd.Parameters.AddWithValue("@OrderId", orderId);
                                cmd.ExecuteNonQuery();
                            }
                        }

                        transaction.Commit();
                        Response.Write("<script>alert('订单已取消！');</script>");
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }

        // 申请退款
        private void ProcessRefund(int orderId)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    try
                    {
                        // 更新订单状态为已取消
                        string updateOrderSql = "UPDATE [Order] SET OrderState = '已取消', UpdateAt = GETDATE() WHERE OrderId = @OrderId AND OrderState = '已发货'";
                        using (SqlCommand cmd = new SqlCommand(updateOrderSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@OrderId", orderId);
                            int rowsAffected = cmd.ExecuteNonQuery();

                            if (rowsAffected == 0)
                            {
                                throw new Exception("订单状态已改变，无法申请退款");
                            }
                        }

                        // 更新支付状态为已退款
                        string updatePaymentSql = "UPDATE Payment SET PayState = '已退款', PayTime = GETDATE() WHERE OrderId = @OrderId";
                        using (SqlCommand cmd = new SqlCommand(updatePaymentSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@OrderId", orderId);
                            cmd.ExecuteNonQuery();
                        }

                        transaction.Commit();
                        Response.Write("<script>alert('退款申请已提交，订单已取消！');</script>");
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }

        // 确认收货
        private void ConfirmOrder(int orderId)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();

                // 更新订单状态为已完成
                string updateOrderSql = "UPDATE [Order] SET OrderState = '已完成', UpdateAt = GETDATE() WHERE OrderId = @OrderId AND OrderState = '已发货'";
                using (SqlCommand cmd = new SqlCommand(updateOrderSql, conn))
                {
                    cmd.Parameters.AddWithValue("@OrderId", orderId);
                    int rowsAffected = cmd.ExecuteNonQuery();

                    if (rowsAffected == 0)
                    {
                        throw new Exception("订单状态已改变，无法确认收货");
                    }
                }

                Response.Write("<script>alert('确认收货成功，订单已完成！');</script>");
            }
        }

        // 获取订单状态对应的CSS类
        protected string GetOrderStateClass(string orderState)
        {
            switch (orderState)
            {
                case "待支付":
                    return "state-pending";
                case "已支付":
                    return "state-paid";
                case "已发货":
                    return "state-shipped";
                case "已完成":
                    return "state-completed";
                case "已取消":
                    return "state-cancelled";
                default:
                    return "";
            }
        }
    }
}